package com.xy.xymail.product.exception;

/**
 * @author xiaye
 * @create 2020-06-03-19:28
 */

import com.xy.common.exception.BizCodeEnume;
import com.xy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 集中出里所有异常
 */
@RestControllerAdvice(basePackages = "com.xy.xymail.product.controller")
@Slf4j
public class XymailExceptionControllerAdvice {

    /**
     * 如果接受到了参数检验异常，那么就走这个方法，返回定义好的状态码和消息，并且将具体的参数和错误，封装并且返回
     * @param e  接受到的异常
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String > errorMap = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleValidException(Throwable throwable){
        log.error("数据校验出现问题{},异常类型{}",throwable.getMessage(),throwable.getClass());

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }


}
